#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智慧童话世界 - 最小化演示版本
用于快速验证核心功能
"""

from flask import Flask, render_template, request, jsonify
import json
import uuid
from datetime import datetime

app = Flask(__name__)

# 模拟故事数据
STORY_TEMPLATES = {
    "勇敢与友谊": {
        "title": "勇敢的{name}和神奇的友谊",
        "opening": "在一个阳光明媚的早晨，{name}发现了一个神秘的花园...",
        "choices": [
            "走进花园探索",
            "先观察一下周围",
            "寻找其他小朋友一起去"
        ]
    },
    "神奇的森林": {
        "title": "{name}的森林大冒险",
        "opening": "小{name}在森林里迷路了，突然听到了奇怪的声音...",
        "choices": [
            "跟着声音走",
            "爬到树上看看",
            "大声呼救"
        ]
    },
    "海底探险": {
        "title": "{name}的海底奇遇记",
        "opening": "戴着神奇潜水镜的{name}潜入了深蓝的海底世界...",
        "choices": [
            "游向发光的珊瑚",
            "跟着小鱼群",
            "探索神秘的洞穴"
        ]
    }
}

# 存储用户会话
user_sessions = {}

@app.route('/')
def index():
    """主页"""
    return render_template('simple.html')

@app.route('/start_story', methods=['POST'])
def start_story():
    """开始新故事"""
    try:
        data = request.json
        child_name = data.get('child_name', '小朋友')
        theme = data.get('theme', '勇敢与友谊')
        age_group = data.get('age_group', '6-8')
        interests = data.get('interests', [])
        
        # 生成故事ID
        story_id = str(uuid.uuid4())
        
        # 获取故事模板
        template = STORY_TEMPLATES.get(theme, STORY_TEMPLATES["勇敢与友谊"])
        
        # 生成故事内容
        story = {
            "id": story_id,
            "title": template["title"].format(name=child_name),
            "content": template["opening"].format(name=child_name),
            "choices": template["choices"],
            "chapter": 1,
            "theme": theme,
            "child_name": child_name,
            "age_group": age_group,
            "interests": interests
        }
        
        # 保存会话
        user_sessions[story_id] = {
            "story": story,
            "history": [story["content"]],
            "created_at": datetime.now().isoformat()
        }
        
        return jsonify({
            "success": True,
            "story": story,
            "message": "故事生成成功！"
        })
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        })

@app.route('/make_choice', methods=['POST'])
def make_choice():
    """处理用户选择"""
    try:
        data = request.json
        story_id = data.get('story_id')
        choice = data.get('choice')
        
        if story_id not in user_sessions:
            return jsonify({
                "success": False,
                "error": "故事会话不存在"
            })
        
        session = user_sessions[story_id]
        current_story = session["story"]
        
        # 根据选择生成下一章节
        next_content = generate_next_chapter(current_story, choice)
        
        # 更新故事
        current_story["chapter"] += 1
        current_story["content"] = next_content["content"]
        current_story["choices"] = next_content["choices"]
        
        # 更新历史
        session["history"].append(f"选择: {choice}")
        session["history"].append(next_content["content"])
        
        return jsonify({
            "success": True,
            "next_story": current_story,
            "message": "故事继续..."
        })
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        })

def generate_next_chapter(story, choice):
    """生成下一章节内容"""
    name = story["child_name"]
    chapter = story["chapter"]
    theme = story["theme"]
    
    # 简单的故事生成逻辑
    if theme == "勇敢与友谊":
        if "探索" in choice:
            content = f"{name}勇敢地走进了花园，发现了一只受伤的小兔子..."
            choices = ["帮助小兔子", "寻找兔子的家", "带小兔子去找医生"]
        elif "观察" in choice:
            content = f"{name}仔细观察后，发现花园里有很多奇特的植物..."
            choices = ["触摸发光的花朵", "采集一些种子", "画下这些植物"]
        else:
            content = f"{name}找到了其他小朋友，大家一起进入了花园..."
            choices = ["分头探索", "一起行动", "制定探索计划"]
    
    elif theme == "神奇的森林":
        if "声音" in choice:
            content = f"{name}跟着声音找到了一只会说话的猫头鹰..."
            choices = ["询问回家的路", "请求猫头鹰的帮助", "和猫头鹰交朋友"]
        elif "树上" in choice:
            content = f"{name}爬到树上，看到了远处的村庄和一条小河..."
            choices = ["朝村庄方向走", "沿着小河走", "继续在树上观察"]
        else:
            content = f"{name}大声呼救，引来了森林里的小动物们..."
            choices = ["请动物们帮忙", "跟着动物们走", "和动物们一起玩"]
    
    else:  # 海底探险
        if "珊瑚" in choice:
            content = f"{name}游向珊瑚，发现了一座美丽的海底城堡..."
            choices = ["进入城堡", "绕着城堡游泳", "寻找城堡的主人"]
        elif "鱼群" in choice:
            content = f"{name}跟着鱼群游到了一个神秘的海底花园..."
            choices = ["采集海底花朵", "和鱼儿们玩耍", "探索花园深处"]
        else:
            content = f"{name}进入洞穴，发现了闪闪发光的宝藏..."
            choices = ["拿一些宝藏", "继续探索洞穴", "寻找宝藏的主人"]
    
    # 如果章节数过多，提供结束选项
    if chapter >= 5:
        choices.append("结束这个美妙的故事")
    
    return {
        "content": content,
        "choices": choices
    }

@app.route('/story_status')
def story_status():
    """获取故事状态"""
    return jsonify({
        "active_sessions": len(user_sessions),
        "total_stories": len(user_sessions),
        "app_status": "运行中"
    })

if __name__ == '__main__':
    print("""
╔══════════════════════════════════════════════════════════════╗
║                    🌟 智慧童话世界 🌟                        ║
║                AI可选分支剧情童话书应用                       ║
║                     最小化演示版本                           ║
╚══════════════════════════════════════════════════════════════╝

🚀 应用启动中...
📱 请在浏览器中访问: http://localhost:5000
🛑 按 Ctrl+C 停止应用
    """)
    
    app.run(host='0.0.0.0', port=5000, debug=True)